package net.starwifi.duobao.interceptor;

import net.starwifi.duobao.SettingUtils;
import net.starwifi.duobao.service.WXUserService;
import net.starwifi.wx.dto.UserInfoByCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * 微信绑定拦截（该拦截下的url必须是已经取得微信授权的地址）
 * Created by Administrator on 2016/1/27.
 */
public class WXUserAuthInterceptor extends HandlerInterceptorAdapter {


    @Value("${url_escaping_charset}")
    private String urlEscapingCharset;

    @Resource
    private WXUserService wxUserService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String  Openid = (String) request.getSession().getAttribute("wx_openid");
        if(Openid!=null){
            return true;
        }
        String userAgent=request.getHeader("User-Agent");
        String code=request.getParameter("code"); //如果来源是微信授权返回
        if(userAgent.contains("MicroMessenger")&&code!=null){
            UserInfoByCode userInfoByCode=wxUserService.getUserInfo(code);
            if(userInfoByCode!=null){
                session.setAttribute("wxCode",code);
                session.setAttribute("wx_openid",userInfoByCode.getOpenid());
                return true;
            }
        }
        timeOut(request,response,handler);
        return  false;
    }


    /** 跳转到微信进行授权*/
    public void timeOut(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        String userAgent=request.getHeader("User-Agent");
        if(userAgent.contains("MicroMessenger")){
            String code= net.starwifi.duobao.utils.StringUtils.getUUID();
            String redirectUrl = request.getQueryString() != null ? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI();
            request.getSession().setAttribute("wx_code",code);
            String baseUrl= SettingUtils.get("siteUrl");
            String loginUrl=wxUserService.getUserAuthUrl(baseUrl+redirectUrl,"snsapi_userinfo",code);
            response.sendRedirect(loginUrl);
        }else{
            String errorWX="/error-wx";//需要微信授权，但是用户在非微信环境
            response.sendRedirect(errorWX);
        }
    }



}
